package com.neuedu.nep.SceneManager;

import com.neuedu.nep.controller.BaseController;
import com.neuedu.nep.controller.ControllerManager;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.util.HashMap;
import java.util.Map;

public class SceneManager {
    private Stage primaryStage;
    private final Map<String, Scene> scenes=new HashMap<String, Scene>();
    private String currentSceneID;

    private static SceneManager instance=null;

    private SceneManager() {};

    public static SceneManager getInstance() {
        if(instance==null) {
            instance=new SceneManager();
        }
        return instance;
    }


    public void switchScene(String sceneID,Object ... params) {
        try{
            if(!scenes.containsKey(sceneID)) {
                FXMLLoader fxmlLoader=new FXMLLoader();
                fxmlLoader.setLocation(SceneManager.class.getResource("/com/neuedu/nep/View/"+sceneID+".fxml"));
                Parent root = fxmlLoader.load();

                ControllerManager.registerController(sceneID,fxmlLoader.getController());
                Scene scene=new Scene(root);
                scenes.put(sceneID,scene);
            }

            Scene scene=scenes.get(sceneID);
            BaseController controller=ControllerManager.getController(sceneID);

            if(controller!=null) {
                controller.onSceneActivated(params);
            }

            if(currentSceneID!=null) {
                BaseController currentController=ControllerManager.getController(currentSceneID);
                if(currentController!=null) {
                    currentController.onSceneDeactivated();
                }
            }
            primaryStage.setScene(scene);
            currentSceneID=sceneID;

            primaryStage.show();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void setStage(Stage primaryStage) {
        this.primaryStage=primaryStage;
    }

    public void clearSceneCache(String sceneID) {
        scenes.remove(sceneID);
        ControllerManager.disposeController(sceneID);
    }
}
